'''评论视图'''
from django.http import Http404
from rest_framework import generics, status
from rest_framework.response import Response
from rest_framework.decorators import api_view, authentication_classes, permission_classes
from ..models import Comment, Doc
from ..serializers import CommentSerializer

class CommentList(generics.ListAPIView):
    '''评论列表'''
    queryset = Comment.objects.all()
    serializer_class = CommentSerializer
    authentication_classes = (())
    permission_classes = (())

    def list(self, request, *args, **kwargs):
        queryset = self.get_queryset()
        doc_id = self.request.query_params.get('docId', None)
        if doc_id is None:
            raise Http404
        else:
            queryset = queryset.filter(doc__id=doc_id)
        serializer = CommentSerializer(queryset, many=True)
        return Response(serializer.data)

@api_view(['post'])
@permission_classes(())
def publish_comment(request):
    '''
    发表评论
    '''
    content = request.data['content']
    doc_id = request.data['docId']
    if request.user.is_authenticated:
        user = request.user
    else:
        user = None
    try:
        doc = Doc.objects.get(pk=doc_id)
    except Doc.DoesNotExist:
        raise Http404

    Comment.objects.create(
        doc=doc,
        user=user,
        content=content
    )
    return Response(status=status.HTTP_201_CREATED)
